<?php

class Adept_Component_List extends Adept_Component_Composite
{

    protected $from;
    protected $key;
    protected $useValue = false;
    protected $useKey = false;
    protected $value;
    protected $valid;

    public function processRestore()
    {
        $this->first();
        while ($this->valid) {
            parent::processRestore();
            $this->next();
        }
    }

    public function processRequest()
    {
        $this->first();
        while ($this->valid) {
            parent::processRequest();
            $this->next();
        }
    }

    public function processSave()
    {
        $this->first();
        while ($this->valid) {
            parent::processSave();
            $this->next();
        }
    }

    public function render()
    {
        $this->first();
        while ($this->valid) {
            parent::render();
            $this->next();
        }
    }

    protected function first() {
        $this->list = $this->getFrom();
        if (!is_array($this->list)) {
            $this->valid = false;
            return false;
        }

        reset($this->list);
        $this->valid = count($this->list) > 0;
        $this->updateKeyAndValue();
    }

    protected function next() {
        $this->valid = (next($this->list) !== false);
        $this->updateKeyAndValue();
    }

    protected function updateKeyAndValue() {
        if (!$this->valid) {
            return ;
        }
        $context = Adept_Context::getInstance();
        if ($this->useValue) {
            $context[$this->value] = current($this->list);
        }
        if ($this->useKey) {
            $context[$this->key] = key($this->list);
        }
    }


    public function getFrom() {
        if (!is_null($this->from)) {
            return $this->from;
        }
        return $this->getValueOfBinding('from', null);
    }

    public function setFrom($from) {
        $this->from = $from;
    }

    public function getValue() {
        return $this->value;
    }

    public function setValue($value) {
        $this->value = $value;
        $this->useValue = true;
    }

    public function getKey() {
        return $this->key;
    }

    public function setKey($key) {
        $this->key = $key;
        $this->useKey = true;
    }

    public function hasRednerer() {
        return false;
    }

}